package com.logicbus.service;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.logicbus.backend.AbstractServant;
import com.logicbus.backend.Context;
import com.logicbus.backend.message.JsonMessage;
import com.logicbus.backend.message.XMLMessage;
import com.logicbus.backend.message.YamlMessage;
import com.logicbus.models.servant.ServiceDescription;

/**
 * Helloworld
 * 
 * <br>
 * 一个小小的测试服务，向客户端说了声Helloworld
 * 定义在/com/logicbus/service/servant.xml中，具体配置如下:<br>
 * 
 * {@code 
 * <service
 * id="Helloworld"
 * name="Helloworld"
 * note="Hello world,我的第一个Logicbus服务"
 * visible="public"
 * module="com.logicbus.service.Helloworld">
 *     <properties>
 *         <parameter id="welcome" value="北京欢迎你."/>
 *     </properties>
 * </service>
 * }
 * 
 * <br>
 * 如果配置在服务器中，访问地址为：<br>
 * {@code
 * http://[host]:[port]/[webcontext]/services/demo/logicbus/Helloworld 
 * }
 * 
 * <br>
 * 本实现支持在服务描述信息中定义参数,参数如下：<br>
 * - welcome:用于出现不同的欢迎语
 * 
 * @author duanyy
 * @version 1.4.0 [20141117 duanyy] <br>
 * - 将MessageDoc和Context进行合并整合 <br>
 *
 * @version 1.6.12.27 [20190403 duanyy] <br>
 * - 增加对yaml的支持 <br>
 */
public class Helloworld extends AbstractServant {
	protected String welcome;

	@Override
	protected void onDestroy() {

	}

	@Override
	protected void onCreate(ServiceDescription sd) {
		welcome = sd.getProperties().GetValue("welcome", "Welcome to Logic Bus Server!");
	}

	@Override
	protected int onJson(Context ctx) {
		JsonMessage msg = (JsonMessage)ctx.asMessage(JsonMessage.class);
		msg.getRoot().put("welcome", welcome);
		return 0;
	}
	
	@Override
	protected int onYaml(Context ctx){
		YamlMessage msg = (YamlMessage)ctx.asMessage(YamlMessage.class);
		msg.getRoot().put("welcome", welcome);
		return 0;
	}
	
	@Override
	protected int onXml(Context ctx){
		XMLMessage msg = (XMLMessage)ctx.asMessage(XMLMessage.class);		
		Element root = msg.getRoot();
		Document doc = root.getOwnerDocument();
		root.appendChild(doc.createTextNode( welcome));		
		return 0;
	}
}
